package http

import (
	"encoding/json"
	"io/ioutil"
	http2 "net/http"
	"time"
	"watcher/server/config"
	"watcher/server/dao"
)

type WriterRequest struct {
	Time        time.Time
	Tags        map[string]string
	Fields      map[string]interface{}
	Measurement string
}

func Writer(response http2.ResponseWriter, r *http2.Request) {
	var responseByte []byte
	var err = NewHttpError(405, "Method Not Allowed")
	switch r.Method {
	case "POST":
		responseByte, err = postWriter(r)
		if err == nil {
			response.Write(responseByte)
			return
		}
	}
	err.Write(response)
}

func postWriter(r *http2.Request) ([]byte, *HttpError) {
	b, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		return nil, NewHttpError(http2.StatusInternalServerError, err.Error())
	}
	var data dao.InfluxRecord
	err = json.Unmarshal(b, &data)
	if err != nil {
		return nil, NewHttpError(http2.StatusInternalServerError, err.Error())
	}
	db, err := dao.NewInfluxDB(config.Config.Influxdb)
	if err != nil {
		return nil, NewHttpError(500, err.Error())
	}
	db.InsertRecord(data)
	return []byte("Hello world"), nil
}
